package com.parq.ie.google.customsearch;

import java.io.StringReader;
import java.util.Iterator;

import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class CSResult {

	private long numberOfResults;
	private NodeList results; 
	
	public CSResult(String resultsFeed)throws Exception{
		InputSource input=new InputSource(new StringReader(resultsFeed));
		input.setEncoding("UTF-8");
		
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setNamespaceAware(true);
		DocumentBuilder builder=factory.newDocumentBuilder();
		Document doc = builder.parse(input);
		results=populateCSResult(doc);
	}
	
	protected NodeList populateCSResult(Document is) throws Exception {
		
		XPathFactory xpathFactory=XPathFactory.newInstance();
		
		NamespaceContext ctx = new NamespaceContext() {
		                public String getNamespaceURI(String prefix) {
		                    String uri;
		                    if (prefix.equals("atom"))
		                        uri = "http://www.w3.org/2005/Atom";
		                    else if (prefix.equals("opensearch"))
		                        uri = "http://a9.com/-/spec/opensearch/1.1/";
		                    else
		                        uri = null;
		                    return uri;
		                }
		                       public Iterator getPrefixes(String val) {
		                           return null;
		                       }
		                       public String getPrefix(String uri) {
		                           return null;
		                       }
		                   };

		XPath xpath = xpathFactory.newXPath();		
		xpath.setNamespaceContext(ctx);
		
		NodeList result = (NodeList)xpath.evaluate("/atom:feed/atom:entry/atom:link/@href", is, XPathConstants.NODESET);
		
		try{
		String results = (String)xpath.evaluate("/atom:feed/opensearch:totalResults", is, XPathConstants.STRING);
		this.numberOfResults=Long.parseLong(results);
		}catch(Exception e){
			throw new Exception("Unable to parse the number of total results from google.");
		}

		return result;
	}

	public long getNumberOfResults() {
		return numberOfResults;
	}

	public NodeList getResults() {
		return results;
	}
}
